﻿#include "EnrollFingerprintDialog.h"
#include "ui_EnrollFingerprintDialog.h"
#include <QDebug>
#include <QMessageBox>

EnrollFingerprintDialog::EnrollFingerprintDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EnrollFingerprintDialog)
{
    ui->setupUi(this);
    m_enroll.setFingerprintCacheDB(&m_cacheDB);
    connect(ui->pushButtonEnroll, SIGNAL(clicked(bool)),this, SLOT(onEnroll()));
    m_reader.openDevice();
    m_reader.beginCapture();
    connect(&m_reader, SIGNAL(onFingerprintReceived(QImage,QByteArray)), this, SLOT(onFingerprintReceived(QImage,QByteArray)));
}

void EnrollFingerprintDialog::accept()
{

}

void EnrollFingerprintDialog::onFingerprintReceived(QImage image, QByteArray fpTemplate)
{
    ui->labelImage->setPixmap(QPixmap::fromImage(image));
}

EnrollFingerprintDialog::~EnrollFingerprintDialog()
{
    if(m_reader.isRunning())
    {
        m_reader.cancelCapture();
        m_reader.wait(150);
    }
    m_reader.closeDevice();
    delete ui;
}

void EnrollFingerprintDialog::onEnroll()
{
    QString pw1 = ui->lineEditPassword->text();
    QString pw2 = ui->lineEditPassword_2->text();

    if(pw1.isEmpty())
    {
        QMessageBox box;
        box.setText(QString::fromUtf8(u8"请先输入密码！"));
        box.exec();
        return;
    }
    if(pw1 != pw2)
    {
        QMessageBox box;
        box.setText(QString::fromUtf8(u8"两次输入的密码不同，请重新输入！"));
        ui->lineEditPassword->clear();
        ui->lineEditPassword_2->clear();
        box.exec();
        return;
    }
    m_enroll.beginEnroll(&m_reader);
    connect(&m_enroll, SIGNAL(fingerprintAccepted()), this, SLOT(onFingerprintAccepted()));
    connect(&m_enroll, SIGNAL(fingerprintRejected()), this, SLOT(onFingerprintRejected()));
    connect(&m_enroll, SIGNAL(enrollFinished(QByteArray)), this, SLOT(onEnrollFinished(QByteArray)));

    ui->labelTip->setText("Doing register, please press your finger 3 times!");
}

void EnrollFingerprintDialog::onFingerprintRejected()
{
    ui->labelTip->setText("Please press the same finger while registering");
}

void EnrollFingerprintDialog::onFingerprintAccepted()
{
    ui->labelTip->setText("please press your finger again");
}

void EnrollFingerprintDialog::onEnrollFinished(QByteArray regTemplate)
{

    ui->labelTip->setText(u8"指纹注册成功！");
    m_regTemplate = regTemplate;
    done(QDialog::Accepted);
}

QString EnrollFingerprintDialog::name()
{
    return ui->lineEditName->text();
}

QString EnrollFingerprintDialog::password()
{
    return ui->lineEditPassword->text();
}

int EnrollFingerprintDialog::user_id()
{
    return ui->lineEditFingerID->text().toInt();
}

QByteArray EnrollFingerprintDialog::fpTemplate()
{
    return m_regTemplate;
}
